package com.eco.fanliapp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.AppGoodsMapper;
import com.eco.fanliapp.dao.SyTimePeriodGoodsMapper;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.DateFormatUtils;
import com.eco.fanliapp.utils.DateUtils;
import com.eco.fanliapp.vo.SyTimePeriodGoodsVo;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-09-09
 */
@Service
public class SyTimePeriodGoodsServiceImpl extends ServiceImpl<SyTimePeriodGoodsMapper, SyTimePeriodGoods> implements ISyTimePeriodGoodsService {
    private static final Logger log = LoggerFactory.getLogger(SyTimePeriodGoodsServiceImpl.class);
    @Autowired
    private SyTimePeriodGoodsMapper syTimePeriodGoodsMapper;
    @Autowired
    private AppGoodsMapper appGoodsMapper;
    @Autowired
    private ISyTimePeriodService syTimePeriodService;
    @Autowired
    private IAppGoodsService appGoodsService;
    @Autowired
    private ISyTimePeriodGoodsService syTimePeriodGoodsService;
	@Autowired
	private ISyLabelTypeService syLabelTypeService;
	@Autowired
	private ISyLabelGoodsService syLabelGoodsService;

	@Autowired
    private IAppGoodsService iAppGoodsService;

    @Override
    public List<SyTimePeriodGoods> pageSyTimePeriodList(Integer pageNum, Integer pageSize, Integer tableId) {
        return syTimePeriodGoodsMapper.pageSyTimePeriodList(pageNum, pageSize, tableId);
    }

    @Override
    public ServerResponse saveSyTimePeriodGoods(SyTimePeriodGoods syTimePeriodGoods,Integer userId) {
        if(syTimePeriodGoods.getTableId() == null){//根据商品id新增秒杀商品
            if(StringUtils.isEmpty(syTimePeriodGoods.getPeriodId()) || StringUtils.isEmpty(syTimePeriodGoods.getItemId()) ){
                return ServerResponse.createByErrorMessage("参数有误");
            }
            Date periodGoodsTime = syTimePeriodGoods.getPeriodGoodsTime();
            String strPeriodGoodsTime = DateFormatUtils.getNowDateDay(periodGoodsTime == null ? new Date():periodGoodsTime);
            SyTimePeriod syTimePeriod = syTimePeriodService.getById(syTimePeriodGoods.getPeriodId());
            AppGoods appGoods = new AppGoods();
            appGoods.setItemid(syTimePeriodGoods.getItemId().toString());
            ServerResponse serverResponse = iAppGoodsService.addAppGoods(appGoods, userId);
            if(serverResponse.getStatus() != 200)return  serverResponse;
            String date = strPeriodGoodsTime + " "+syTimePeriod.getPeriodTime()+":00";
            ServerResponse serverResponse1 = this.thirdSave(date, syTimePeriod.getPeriodTime(), syTimePeriodGoods.getItemId().toString());
            return serverResponse1;
        }
        boolean b = this.updateById(syTimePeriodGoods);
        if(b)return ServerResponse.createBySuccessMessage("操作成功");
        return ServerResponse.createByErrorMessage("操作失败");
    }

    @Override
    public List<SyTimePeriodGoodsVo> selectLimitList(Integer pageNum, Integer pageSize, Integer tableId,String periodGoodsTime) {
        return syTimePeriodGoodsMapper.selectLimitList(pageNum,pageSize,tableId,periodGoodsTime);
    }

    @Override
    public List<AppGoods> getTimePeriodGoods(String startTime,String endTime) {
        List<AppGoods> list = appGoodsMapper.getTimePeriodGoods(startTime,endTime);
        return list;
    }

    @Override
    public ServerResponse thirdSave(String date, String hour, String itemId) {
        //校验参数
        if(date==null || "".equals(date)){
            return ServerResponse.createByErrorMessage("参数不能为空");
        }
        if(hour==null || "".equals(hour)){
            return ServerResponse.createByErrorMessage("hour参数不能为空");
        }
        if(itemId==null || "".equals(itemId)){
            return ServerResponse.createByErrorMessage("itemId参数不能为空");
        }

        //日期大于或者等于当前日期
        long startTime = DateFormatUtils.getMillis(new Date());//当前时间
        Long aLong = null;//传入的日期
        try {
            aLong = DateFormatUtils.stringToLong(date,DateFormatUtils.STANDARD_FORMAT);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if(aLong - startTime < 0){
            return ServerResponse.createByErrorMessage("日期不能小于当前日期");
        }

        //时间段是否匹配
        QueryWrapper<SyTimePeriod> query = new QueryWrapper<>();
        query.eq("period_time",hour);
        query.eq("enable",1);
        query.eq("deleted",0);
        List<SyTimePeriod> periods = syTimePeriodService.list(query);

        if(CollectionUtils.isEmpty(periods)){
			return ServerResponse.createByErrorMessage("该时间段无法匹配对应的秒杀时间段");
		}

		//查询秒杀标签是否存在
		QueryWrapper<SyLabelType> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("label_name","秒杀");
        queryWrapper.eq("enable",1);
        queryWrapper.eq("deleted",0);
		List<SyLabelType> list = syLabelTypeService.list(queryWrapper);
		if(CollectionUtils.isEmpty(list)){
			return ServerResponse.createByErrorMessage("未获取到秒杀标签类型");
		}
		SyLabelType syLabelType = list.get(0);

		QueryWrapper<SyLabelGoods> queryWrapper2 = new QueryWrapper<>();
		queryWrapper2.eq("item_id",itemId);
		queryWrapper2.eq("label_type_id",syLabelType.getTableId().toString());
		queryWrapper2.eq("label_code",syLabelType.getLabelCode());
		queryWrapper2.eq("enable",1);
		queryWrapper2.eq("deleted",0);
		List<SyLabelGoods> list2 = syLabelGoodsService.list(queryWrapper2);
		if(!CollectionUtils.isNotEmpty(list2)){
			//return ServerResponse.createByErrorMessage("该标签对应的商品已经存在！");
            //保存标签商品
            SyLabelGoods labelGoods = new SyLabelGoods();
            labelGoods.setItemId(itemId);
            labelGoods.setLabelTypeId(syLabelType.getTableId().toString());
            labelGoods.setLabelCode(syLabelType.getLabelCode());
            syLabelGoodsService.save(labelGoods);
		}
		//秒杀库是否已经存在
		QueryWrapper<SyTimePeriodGoods> queryWrapper1 = new QueryWrapper<>();
		queryWrapper1.eq("item_id",itemId);
		queryWrapper1.eq("enable",1);
		queryWrapper1.eq("deleted",0);
        String[] split = date.split(" ");
        queryWrapper1.like("period_goods_time",split[0]);
        List<SyTimePeriodGoods> list1 = syTimePeriodGoodsService.list(queryWrapper1);
		if(CollectionUtils.isNotEmpty(list1)){
			return ServerResponse.createByErrorMessage("该商品在秒杀商品中已存在！");
		}

		//获取商品
		AppGoods appGood = appGoodsService.findAppGoodsByItemId(itemId);
		if(appGood == null){
			return ServerResponse.createByErrorMessage("该时间段无法匹配对应的秒杀时间段");
		}
		//获取时间段
		SyTimePeriod syTimePeriod = periods.get(0);

		//保存商品
		SyTimePeriodGoods stpg = new SyTimePeriodGoods();
        stpg.setPeriodId(syTimePeriod.getTableId());
        stpg.setPeriodTime(syTimePeriod.getPeriodTime());
        //商品id
        log.info("商品id为{}",appGood.getItemid());
        if(appGood.getItemid()!=null && !"".equals(appGood.getItemid())){
            stpg.setItemId(Long.valueOf(appGood.getItemid()));
        }
        stpg.setItemTitle(appGood.getItemtitle());
        stpg.setItemPic(appGood.getItempic());
        stpg.setItemNum(appGood.getCouponsurplus() == null ? appGood.getCouponnum() : appGood.getCouponsurplus());//取优惠券剩余数量
        stpg.setItemDesc(appGood.getItemdesc());
        stpg.setPeriodGoodsTime(DateUtils.datestr2Date(date,DateUtils.DATE_FORMAT_YYYYMMDDHHMMSS));
        stpg.setTkMoney(new BigDecimal(appGood.getTkmoney() == null ? "0":appGood.getTkmoney()));
        //原价
        log.info("商品原价{}",appGood.getItemprice());
        if(appGood.getItemprice()!=null && !"".equals(appGood.getItemprice())){
            stpg.setOriginalPrice(BigDecimal.valueOf(Double.parseDouble(appGood.getItemprice())));
        }
        //折扣价
        log.info("商品折扣价{}",appGood.getItemendprice());
        if(appGood.getItemendprice()!=null && !"".equals(appGood.getItemendprice())){
            stpg.setDiscountPrice(BigDecimal.valueOf(appGood.getItemendprice()));
        }
        //保存商品
        syTimePeriodGoodsService.save(stpg);
        return ServerResponse.createBySuccessMessage("添加秒杀商品成功！");
    }

	@Override
	public Integer updateBatch(List<Long> lt) {

		return syTimePeriodGoodsMapper.updateBatch(lt);
	}

    /**
     * 根据商品ID查询限时秒杀商品
     * @param itemId
     * @return
     */
    @Override
    public SyTimePeriodGoods findPeriodGoodsById(Long itemId) {
        return syTimePeriodGoodsMapper.findPeriodGoodsById(itemId);
    }
}
